package uni.UNIBEE7B8D.Presenter;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import org.json.JSONException;

import java.text.ParseException;

import uni.UNIBEE7B8D.CommonTool.HttpUrl;
import uni.UNIBEE7B8D.CommonTool.OkHttpUtil;
import uni.UNIBEE7B8D.Enty.Result;
import uni.UNIBEE7B8D.view.User.LoginContract;

public class LoginPersenter implements LoginContract.LoginPresenter {

    LoginContract.LoginView loginView;

    public LoginPersenter(LoginContract.LoginView loginView) {
        this.loginView = loginView;
    }

    @Override
    public void sendcode(String phone) {
        if(TextUtils.isEmpty(phone)){
            loginView.Toast("请输入手机号");
        }else{
            new OkHttpUtil().getJson(HttpUrl.sendcode + "&phone=" + phone, new OkHttpUtil.HttpCallBack() {
                @Override
                public void onSusscess(String data) throws JSONException, ParseException {
                    Result result = new Gson().fromJson(data,Result.class);
                    loginView.Toast(result.getMessage());
                }

                @Override
                public void onError(String meg) {
                    super.onError(meg);
                    loginView.Toast(meg);
                }
            });
        }



    }

    //手机 验证码登录
    @Override
    public void login(String phone, String code) {
        if(TextUtils.isEmpty(phone)){
            loginView.Toast("请输入手机号");
        }else if(TextUtils.isEmpty(code)){
            loginView.Toast("请输入验证码");
        }else{
            new OkHttpUtil().getJson(HttpUrl.login + "?phone=" + phone+"&code="+code+"&v_num=1.0.0", new OkHttpUtil.HttpCallBack() {
                @Override
                public void onSusscess(String data) {
                    Log.d("==",data);
                    // true表示是注册用户，反之是登录用户。注册用户需要进入下面这个界面
                    Result result = new Gson().fromJson(data,Result.class);
                    if (result.isSuccess()){
                        loginView.Toast(result.getMessage());
                    }else{
                        loginView.login(result.getResult());
                    }
                }

                @Override
                public void onError(String meg) {
                    super.onError(meg);
                    loginView.Toast(meg);
                }
            });
        }

    }
}
